package com.example.questionnaires.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.questionnaires.common.PageResult;
import com.example.questionnaires.common.Result;
import com.example.questionnaires.dto.UserDTO;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.form.LoginForm;
import com.example.questionnaires.form.RegisterForm;
import com.example.questionnaires.service.UserService;
import com.example.questionnaires.utils.UserContext;
import com.example.questionnaires.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import java.util.Map;
import java.util.HashMap;
import com.example.questionnaires.common.BusinessException;

@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<UserDTO> login(@RequestBody LoginForm loginForm) {
        return userService.login(loginForm);
    }

    @PostMapping("/register")
    public Result<Void> register(@RequestBody RegisterForm registerForm) {
        return userService.register(registerForm);
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        log.info("获取用户信息");
        User user = UserContext.getCurrentUser();
        log.info("当前用户: {}", user);
        return Result.success(UserContext.getCurrentUser());
    }

    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        log.info("获取用户统计信息");
        User user = UserContext.getCurrentUser();
        log.info("当前用户: {}", user);
        if (user == null) {
            throw new BusinessException("请先登录");
        }
        
        Map<String, Object> statistics = new HashMap<>();
        // TODO: 添加统计信息
        return Result.success(statistics);
    }

    @PostMapping("/logout")
    public Result<Void> logout() {
        UserHolder.removeUser();
        return Result.success();
    }

    @PutMapping("/password")
    public Result<Void> updatePassword(@RequestParam Long userId,
                                     @RequestParam String oldPassword,
                                     @RequestParam String newPassword) {
        userService.updatePassword(userId, oldPassword, newPassword);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @GetMapping("/list")
    public Result<PageResult<User>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return userService.list(page, size);
    }

    @PostMapping
    public Result<Void> add(@RequestBody UserDTO userDTO) {
        return userService.add(userDTO);
    }

    @RequestMapping(value = "/profile", method = RequestMethod.PUT)
    public Result<Void> updateProfile(@RequestBody User user) {
        log.info("更新用户信息: {}", user);
        User currentUser = UserContext.getCurrentUser();
        log.info("当前用户: {}", currentUser);
        if (currentUser == null) {
            throw new BusinessException("请先登录");
        }
        
        user.setId(currentUser.getId());
        userService.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        return userService.deleteById(id);
    }

    @PutMapping("/{id}/password/reset")
    public Result<Void> resetPassword(@PathVariable Long id) {
        return userService.resetPassword(id);
    }

    @PutMapping("/{id}/ban")
    public Result<Void> ban(@PathVariable Long id) {
        return userService.updateStatus(id, 0);
    }

    @PutMapping("/{id}/unban")
    public Result<Void> unban(@PathVariable Long id) {
        return userService.updateStatus(id, 1);
    }
}
